import { useRequest } from 'ahooks';
import {
  Button,
  Space,
  Table,
  Divider,
  Popconfirm,
  message,
} from 'antd';
import Column from 'antd/lib/table/Column';
import React, { useState } from 'react';
import FileSaver from 'file-saver';
import xlsx from 'node-xlsx';

import Detail from './detail';
import * as APIS from '../../../constants/api-constants';
import useExcel from './hooks';


interface Props {
  tableProps: CM.CompanyShow[];
  setPage: (page: number) => void;
  setFresh: () => void;
  total: number;
  listloading: boolean;
  setTotal: (totle: number) => void;
}

export default ({
  tableProps, setPage, setFresh, total, setTotal, listloading
}: Props) => {
  const [showDetail, setShowDetail] = useState(false);
  const [update, setUpdate] = useState(0);

  const [currentCompanyUuid, setCurrentCompanyUuid] = useState<string>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const excelData = useExcel(selectedRowKeys, tableProps);

  /**
   * 删除企业
   */
  const { run: deleteCompany, loading: deleteLoading } = useRequest((id) => (
    {
      url: APIS.DELETE_COMPANY,
      method: 'DELETE',
      data: {
        id
      }
    }
  ), {
    manual: true,
    onSuccess: () => {
      setFresh();
      message.success('删除成功');
    },
    onError: () => {
      message.error('删除失败');
    },
  });

  /**
   * 批量删除企业
   */
  const { run: deleteBatchCompany, loading: deleteBatchLoading } = useRequest(() => (
    {
      url: APIS.BULK_DELETE_COMPANY,
      method: 'DELETE',
      data: {
        batchDeleteArray: selectedRowKeys
      }
    }
  ), {
    manual: true,
    onSuccess: () => {
      setFresh();
      message.success('批量删除成功');
    },
    onError: () => {
      message.error('删除失败');
    },
  });

  /**
   * 批量选择企业
   */
  const onChange = (selectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(selectedRowKeys);
  }
  /**
   * 批量导出
   */
  const handleBatchExport = () => {
    if (excelData.length !== 1) {
      const blob = new Blob(
        [xlsx.build([{
          name: '企业信息', data: excelData
        }])],
        {
          type: 'application/octet-stream',
        }
      );
      FileSaver.saveAs(blob, '企业信息导出表.xlsx');
    }
  }

  return (
    <>
      <Table
        size="middle"
        loading={listloading}
        rowKey={(record) => record.id}
        dataSource={tableProps}
        rowSelection={{
          selectedRowKeys,
          onChange,
        }}
        pagination={{
          onChange: (page) => setPage(page),
          total,
        }}
        footer={() => {
          return (
            <>
              {
                window.localStorage.getItem('identity') === null ?
                  null
                  :
                  <Space>
                    <Button
                      onClick={() => {
                        handleBatchExport();
                      }}>
                      批量导出
                    </Button>
                    <Popconfirm
                      title='确定要批量删除这些企业吗?'
                      onConfirm={() => {
                        deleteBatchCompany();
                      }}
                      okText='Yes'
                      cancelText='No'
                      okButtonProps={{ loading: deleteBatchLoading }}
                    >
                      <Button>批量删除</Button>
                    </Popconfirm>
                  </Space>
              }
            </>
          );
        }}
      >
        <Column title="企业名称" dataIndex="name" key="name" align="center" />
        <Column title="企业类型" dataIndex="type" key="type" align="center" />
        <Column title="医疗领域" dataIndex="medicalField" key="medicalField" align="center" />
        <Column title="主营业务" dataIndex="mainBusiness" key="mainBusiness" align="center" />
        <Column title="成立日期" dataIndex="createDate" key="createDate" align="center" />
        <Column title="所在地" dataIndex="address" key="address" align="center" />
        {
          window.localStorage.getItem('identity') === null ?
            <Column
              title="操作"
              align="center"
              render={(record: CM.CompanyShow) => (
                <Space split={<Divider type="vertical" />}>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      setCurrentCompanyUuid(record?.uuid);
                      setShowDetail(true);
                    }}
                  >
                    详情
                  </Button>
                </Space>
              )}
            />
            :
            <Column
              title="操作"
              align="center"
              render={(record: CM.CompanyShow) => (
                <Space split={<Divider type="vertical" />}>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      setCurrentCompanyUuid(record?.uuid);
                      setUpdate(update + 1)
                      setShowDetail(true);
                    }}
                  >
                    修改
                  </Button>
                  <Popconfirm
                    title="删除后该企业无法找回！是否删除?"
                    onConfirm={() => {
                      deleteCompany(record?.id)
                      setFresh();
                    }}
                    okText="确定"
                    cancelText="取消"
                    okButtonProps={{ loading: deleteLoading }}
                  >
                    <Button type="link" size="small">
                      删除
                    </Button>
                  </Popconfirm>
                </Space>
              )}
            />
        }
      </Table>
      <Detail
        showDetail={showDetail}
        setShowDetail={setShowDetail}
        update={update}
        currentCompanyUuid={currentCompanyUuid}
        setFresh={setFresh}
      />
    </>
  );
};
